package cn.tmall.service.impl;

import cn.tmall.mapper.OrderMapper;
import cn.tmall.pojo.Order;
import cn.tmall.pojo.OrderExample;
import cn.tmall.pojo.OrderItem;
import cn.tmall.pojo.User;
import cn.tmall.service.OrderItemService;
import cn.tmall.service.OrderService;
import cn.tmall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service("OrderServiceImpl")
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;
    @Resource(name = "UserServiceImpl")
    UserService userService;
    @Resource(name = "OrderItemServiceImpl")
    OrderItemService orderItemService;


    @Override
    public void add(Order order) {
        orderMapper.insert(order);
    }

    @Override
    public void delete(int id) {
        orderMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Order order) {
        orderMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public Order get(int id) {
        return orderMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Order> list() {
        OrderExample example = new OrderExample();
        example.setOrderByClause("id desc");
        List<Order> orderList = orderMapper.selectByExample(example);
        this.setUser(orderList);
        return orderList;
    }

    @Override   //添加新order的同时更新orderItem表的oid
    @Transactional(propagation= Propagation.REQUIRED,rollbackForClassName="Exception")  //通过注解进行事务管理
    public float add(Order order, List<OrderItem> orderItemList) {
        float total = 0;
        this.add(order);

        //用来模拟当增加订单后出现异常，观察事务管理是否预期发生。（需要把false修改为true才能观察到）
        if(false)
            throw new RuntimeException();

        for (OrderItem orderItem : orderItemList) {
            orderItem.setOid(order.getId());

            orderItemService.update(orderItem);
            total += orderItem.getNumber() * orderItem.getProduct().getPromotePrice();
        }
        return total;
    }

    @Override
    public List<Order> list(int uid, String excludedStatus) {
        OrderExample example = new OrderExample();
        example.createCriteria().andStatusNotEqualTo(excludedStatus);
        example.setOrderByClause("id desc");
        return orderMapper.selectByExample(example);
    }

    public void setUser(Order order) {
        User user = userService.get(order.getUid());
        order.setUser(user);
    }
    public void setUser(List<Order> orderList) {
        for (Order order : orderList) {
            this.setUser(order);
        }
    }
}
